package net.hubt.itc.ui;

import net.hubt.itc.data.PrefsKeys;
import net.hubt.itc.data.User;
import net.hubt.itc.util.PhoneUtils;
import android.app.Application;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.PreferenceManager;


public class HUBTApplication extends Application implements
		OnSharedPreferenceChangeListener {

	public static final String TAG = HUBTApplication.class.getSimpleName();

	private SharedPreferences mPrefs;

	// global user information
	// userid, userPhone, user base url
	private User mUser;

	@Override
	public void onCreate() {
		super.onCreate();

		initPrefs();
		initUserPrefs();
		setPhoneNumber();
		
	}

	/**
	 * create global references, listen to any changes occur in the preferences
	 */
	protected void initPrefs() {
		mPrefs = PreferenceManager.getDefaultSharedPreferences(this);			
		mPrefs.registerOnSharedPreferenceChangeListener(this);
	}

	protected void initUserPrefs() {
		// user info is changed by 'onSharedPreferenceChanged'
		// user change user's information in preference settings
		if (mUser == null) {
			mUser = new User();
			mUser.setPhoneNo(PhoneUtils.getPhoneNumber(this));
			mUser.setUserId(mPrefs.getString(PrefsKeys.USER_ID, null));
			mUser.setUserClass(mPrefs.getString(PrefsKeys.USER_CLASS_NAME, null));
			mUser.setBaseUrl(mPrefs.getString(PrefsKeys.USER_URL, null));
		}
	}

	/**
	 * @return
	 */
	public User getUserPrefs() {
		initUserPrefs();
		return mUser;
	}

	public void setPhoneNumber() {
		mPrefs.edit()
				.putString(PrefsKeys.USER_SIM_NO,
						PhoneUtils.getPhoneNumber(this)).commit();
	}
	
	public void setClassName(String lop) {
		mPrefs.edit()
				.putString(PrefsKeys.USER_CLASS_NAME, lop).commit();
	}
	
	public String getClassName() {
		return mPrefs.getString(PrefsKeys.USER_CLASS_NAME, null);
	}
	
	public String getPhoneNumber(){
		return PhoneUtils.getPhoneNumber(this);
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {		
		mUser = null;
		
	}

	public User getCurrentUser() {
		return mUser;
	}

	/**
	 * get preferences string values
	 * 
	 * @param key
	 * @param defValue
	 * @return
	 */
	public String getPrefsString(String key, String defValue) {
		if (mPrefs != null) {
			return mPrefs.getString(key, defValue);
		}
		return null;
	}

	protected boolean isPrefsSettingOK() {
		if (mPrefs == null)
			return false;

		return true;
	}

}
